<template>
  <view class="order-page flex flex-col px-32rpx h-full box-border">
    <view class="flex-1 overflow-auto">
      <view class="order-item my-48rpx" v-for="(item, index) in skuList" :key="index">
        <!-- 产品 -->
        <view class="flex justify-between items-center">
          <view class="common-product-list-item-left">
            <up-album :urls="[item.skuImageUrl || defaultImg]"></up-album>
            <view>
              <view class="name">
                {{ item?.skuDescription || '' }}
              </view>
              <view class="sub-name">
                好达威SKU:{{ item.skuCode || '' }}
              </view>
              <view v-if="item.supplierSkuCodes?.filter((code: string) => !!code)?.length" class="sub-name">
                商家SKU:{{ item.supplierSkuCodes.join(',') || '' }}
              </view>
            </view>
          </view>
          <view class="w-110rpx h-50rpx">
            <up-button color="#F53F3F" type="primary" text="无货" size="mini" @click="noGoods(item.id)"></up-button>
          </view>
        </view>
        <!-- 现价 -->
        <view class="mt-20rpx">
          <view class="mb-10rpx text-24rpx">现价</view>
          <view :class="deThousandSeparatFormat(item.skuUnitPrice) > item.oldPrice ? 'red-border' : ''">
            <up-input type="digit" v-model="item.skuUnitPrice" @change="priceChange(item)">
              <template #prefix>
                <up-text :text="item.currency?.unitSymbol" margin="0 3px 0 0" type="tips"></up-text>
              </template>
            </up-input>
          </view>
        </view>
        <!-- 期望货期 -->
        <view class="mt-20rpx">
          <view class="mb-10rpx text-24rpx">到仓货期(天)</view>
          <view>
            <up-input type="number" v-model="item.deliveryDays" @blur="(val) => handleInput(val, item)"
              placeholder="请输入到仓货期">
            </up-input>
          </view>
          <view v-if="item.error" class="text-24rpx text-#F53F3F">{{ item.error }}</view>
        </view>
      </view>
    </view>
    <view class="h-148rpx w-full box-border items-center justify-around flex py-26rpx">
      <up-button color="#1A5FA9" type="primary" text="保存" @click="save"></up-button>
    </view>
  </view>
  <!-- 无货弹窗 -->
  <up-modal :width="328" :show="noGoodsVisible" title="是否确认无货">
    <view class="slot-content">
      确认无货后该SKU将自动从该PO中删除
    </view>
    <template #confirmButton>
      <view class="confirmButton flex justify-center">
        <view class="btn-box mr-32rpx w-264rpx"><up-button :plain="true" text="取消"
            @click="noGoodsVisible = false"></up-button>
        </view>
        <view class="btn-box w-264rpx"><up-button color="#F53F3F" type="primary" text="确认无货"
            @click="confirm"></up-button>
        </view>
      </view>
    </template>
  </up-modal>
</template>

<script setup lang="ts">
import { poManageQueryPoSku, poManageUpdatePoSku, poManageOutOfStockHandling } from "@/genapi/poManage";
import { thousandSeparatFormat, deThousandSeparatFormat } from "@/utils/utils";
import { debounce } from '@antfu/utils'
import defaultImg from "@/static/default.png"

const skuList = ref<any[]>([])
let detailId = ''
const noGoodsVisible = ref(false)
let currentSkuId = ''

onLoad((query) => {
  detailId = query?.id || ''
})

const priceChange = debounce(500, priceChangeFun)
function priceChangeFun(item: any) {
  // 先去掉逗号分隔符
  const price = deThousandSeparatFormat(item.skuUnitPrice)
  // 再插入分隔符
  item.skuUnitPrice = thousandSeparatFormat(price)
}
function handleInput(val: string, item: any) {
  if (+val > 730) {
    item.error = '货期不能超过730天'
    return
  }
  // 使用正则表达式验证输入值是否为正整数
  if (+val >= 1 && /^-?\d*\.?\d*$/.test(val)) { // 小数或整数
    // 正数
    item.deliveryDays = Math.floor(+val).toString();
    item.error = ''
  } else {
    item.deliveryDays = ''
    item.error = '请输入到仓货期'
  }
}
async function getSkuList() {
  const { data } = await poManageQueryPoSku({ poId: detailId, noCancelSku: true })
  if (data?.code !== 200) return
  else {
    const result = data.data
    skuList.value = result.map((item: any) => {
      item.oldPrice = item.skuUnitPrice
      item.skuUnitPrice = thousandSeparatFormat(item.skuUnitPrice)
      if (item.deliveryDays < 1) {
        item.deliveryDays = ''
      }
      item.error = ''
      return item
    })
  }
}
function noGoods(id: string) {
  noGoodsVisible.value = true
  currentSkuId = id
}
async function confirm() {
  const { data } = await poManageOutOfStockHandling([currentSkuId])
  if (data?.code !== 200) return
  else {
    uni.switchTab({
      url: '/pages/orderList/index'
    })
  }
  noGoodsVisible.value = false
}
async function save() {
  const updateList: any[] = []
  if (skuList.value.length) {
    let valid = true
    const newList = skuList.value.map((item: any) => {
      const skuInfo: any = {
        deliveryDays: +item.deliveryDays,
        id: item.id,
        skuUnitPrice: +deThousandSeparatFormat(item.skuUnitPrice)
      }
      updateList.push(skuInfo)
      if (!item.deliveryDays) {
        item.error = '请输入到仓货期'
        valid = false
      } else if (item.deliveryDays > 730) {
        item.error = '货期不能超过730天'
        valid = false
      }
      return item
    })
    skuList.value = [...newList]
    if (!valid) return
    const { data } = await poManageUpdatePoSku({ updateList })
    if (data?.code !== 200) return
    else {
      uni.redirectTo({
        url: `/pages/confirmSubmit/index?id=${detailId}`
      })
    }
  }
}
onShow(async () => {
  getSkuList()
})
</script>
